<template>
    <div class="module">
        <el-row>
            <el-col :span="9" class="font_size_20"><span>企业名称： <i class="blod_style_i">{{accountInfo.enterpriseName}}</i></span></el-col>
            <el-col :span="9" class="font_size_20"><span>平台汇票豆账户可用余额: <i class="draft_i_style">{{accountInfo.availableBalance}} 个</i> </span></el-col>
            <el-col :span="6" style="text-align: right;">
                <el-button size="small" type="primary" @click="onRecharge">充值</el-button>
                <el-button size="small" type="primary" @click="onModify">修改</el-button>
                <el-button size="small" type="primary" plain @click="onModifyLog">访客操作记录</el-button>
            </el-col>
        </el-row>
        <el-row style="margin-top: 50px;">
            <el-col :span="18">
                <span style="font-size: 16px;color: #1C1F33;">收支明细列表：</span>
                <el-date-picker
                v-model="dateRegion"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small">
                </el-date-picker>
                <el-select v-model="beansType" value-key="value" class="select_it_style">
                    <el-option 
                    v-for="(beansType, index) in beansTypes" 
                    :label="beansType.label"
                    :value="beansType.value"
                    :key="index"></el-option>
                </el-select>
                <el-button size="small" @click="onFilterData" type="primary">筛选</el-button>
            </el-col>
            <el-col :span="6" class="defalut_excel" style="text-align: right;">
                <!--<el-button size="small" type="success" @click="onExportExcel">导出Excel</el-button>-->
                <el-button plain size="small" @click="onExportExcel()">导出Excel表格</el-button>
            </el-col>
        </el-row>
        <el-table 
        :data="tableData" 
        :default-sort="{prop: 'createTime', order: 'descending'}"
        stripe 
        style="width: 100%">
            <el-table-column prop="businessId" label="订单号"> </el-table-column>
            <el-table-column prop="createTime" :formatter="formatter" label="时间"> </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column prop="rechargeAmount" label="充值金额（元）">
                <template slot-scope="scope">
                    <span class="income_color">{{scope.row.rechargeAmount}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="income" label="收入（个）">
                <template slot-scope="scope">
                    <span class="income_color">
                        {{!scope.row.income ? '' : '+' + scope.row.income}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="expenditure" label="支出（个）">
                <template slot-scope="scope">
                    <span class="outgo_color">
                        {{!scope.row.expenditure ? '' : '-' + scope.row.expenditure}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="availableBalance" label="汇票豆余额（个）"> </el-table-column>
        </el-table>
        <div class="right clear pagingbar">
            <el-pagination
            @size-change="onSizeChange"
            @current-change="onFlipOver"
            :current-page="pagination.currentPage"
            :page-sizes="pagination.pageSizes"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
            </el-pagination>
        </div>
        <!-- 充值 Dialog -->
        <el-dialog title="请核对并充值" :visible.sync="rechargeDialogVisible" width="30%" center @closed="onCloseRechageDialog">
            <el-form ref="recharge" label-width="120px" :modal="recharge" size="small">
                <el-form-item label="充值金额（元）" label-position="left">
                    <el-input v-model="recharge.money" type="number"></el-input>
                </el-form-item>
                <el-form-item label="兑换比率" label-position="left"> 
                    <el-select v-model="recharge.ratio" value-key="value">
                        <el-option
                        v-for="(ratio, index) in ratios" 
                        :label="ratio.label"
                        :value="ratio.value"
                        :key="index"></el-option>
                    </el-select>
                    <span>兑换汇票豆 （{{ recharge.sum }}） 个</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer submit-btn">
                <el-button size="small" type="info" @click="rechargeDialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="onRechargeSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改 Dialog -->
        <el-dialog title="修改账户汇票豆" :visible.sync="modifyDialogVisible" width="30%" center @closed="onCloseModifyDialog">
            <div class="text_left" style="margin-left: 120px;">
                企业名称： {{accountInfo.enterpriseName }}
            </div>
            <div class="text_left" style="margin-left: 120px;margin-top: 8px;margin-bottom: 6px;">
                平台汇票豆账户可以余额: <span class="income_color">{{accountInfo.availableBalance }}</span>
            </div>
            <el-form ref="recharge" label-width="120px" :modal="recharge" size="small">
                <el-form-item label="" label-position="left">
                    <el-radio-group v-model="modifyForm.operType" size="small">
                        <el-radio-button label="2">+增加</el-radio-button>
                        <el-radio-button label="3">-减少</el-radio-button>
                    </el-radio-group>
                    <el-input
                    v-model="modifyForm.beans" 
                    placeholder="请输入需增减汇票豆个数"
                    type="number"
                    class="draft_int"></el-input>
                </el-form-item>
                <el-form-item label="备注说明" label-position="left"> 
                    <el-input
                    type="textarea"
                    :rows="2"
                    resize="none"
                    placeholder="请输入增减汇票豆的原因"
                    v-model="modifyForm.explain">
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer submit-btn">
                <el-button size="small" type="info" @click="modifyDialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="onModifySubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
    import * as moment from 'moment';
    import { formatter, DateTools } from '@/util/format';
    import math from 'mathjs';
    import Pagination from "@/types/Pagination";

    @Component({
        extends: Pagination
    })
    export default class DraftBeans extends Vue {
        @Prop(String) enterpriseId!:number

        // data
        rechargeDialogVisible = false;
        modifyDialogVisible = false;
        recharge = {
            money: '',
            ratio: 1.1,
            sum: ''
        };
        ratios = [
            { label: '1:1', value: 1},
            { label: '1:1.1', value: 1.1},
            { label: '1:1.2', value: 1.2},
            { label: '1:1.3', value: 1.3},
            { label: '1:1.4', value: 1.4},
            { label: '1:1.5', value: 1.5},
        ];
        modifyForm = {
            beans: '',
            operType: "2",
            explain: ''
        }
        
        accountInfo = {
            availableBalance: 0,
            balance: 0,
            channel: 0,
            createTime: 0,
            enterpriseId: 0,
            enterpriseName: '',
            frozenAmount: 0,
            id: 0,
            isValid: 0,
            totalExpenditure: 0,
            totalIncome: 0,
            totalRecharge: 0,
            updateTime: 0,
        };
        tableData = [];
        formatter = formatter
        dateRegion = []
        // dateRegion = ['2018-01-01', '2018-12-31']
        beansType = ''
        beansTypes = [
            { label: '全部', value: '' },
            { label: '收入', value: 1 },
            { label: '支出', value: 2 }
        ]

        /**
         * 修改汇票豆兑换比率
         */
        @Watch('recharge.ratio')
        ratioChange(newVal:number, oldVal:number) {
            if (this.recharge.money) {
                this.recharge.sum = math.round((newVal * this.recharge.money), 2)
            }
        }
        /**
         * 修改充值金额
         */
        @Watch('recharge.money')
        moneyChange(newVal:number, oldVal:number) {
            this.recharge.sum = math.round((newVal * this.recharge.ratio), 2);
        }

        // methods
        /**
         * 查询所有汇票豆账户列表
         */
        async loadAccountList() {
            let res = await this.$http.post('draftbean/accounts/list', {
                currentPage: this.pagination.currentPage,
                pageSize: this.pagination.pageSize
            })
            if (res.status == 200) {
                let { items, totalNum } = res.data;
                this.tableData = items;
                this.pagination.total = totalNum;
            }
        }

        /**
         * 查询企业汇票豆收支明细
         */
        async getBudgetDetailByEId() {
            if (this.dateRegion == null) {
                this.dateRegion = ['','']
            }
            let res = await this.$http.post('draftbean/accounts/budgetdetail', {
                enterpriseId: this.enterpriseId,
                budget: this.beansType,
                startTime: this.dateRegion[0],
                endTime: this.dateRegion[1],
                currentPage: this.pagination.currentPage,
                pageSize: this.pagination.pageSize
            })
            if (res.status == 200) {
                let { items, totalNum } = res.data;
                this.tableData = items;
                this.pagination.total = totalNum;
            }
        }
        /**
         * 查询企业汇票豆账户
         */
        async getAccountByEId() {
            let res = await this.$http.get(`draftbean/accounts/${this.enterpriseId}`)
            this.accountInfo = res.data;
        }

        /**
         * 修改账户汇票豆
         */
        async updateDraftBeanByEnterpriseId() {
            return this.$http.put('draftbean/accounts/update', {
                enterpriseId: this.enterpriseId,
                operationalAction: this.modifyForm.operType,
                draftBean: this.modifyForm.beans,
                remark: this.modifyForm.explain
            })
        }

        /**
         * 充值汇票豆
         */
        async rechargeDraftBeans() {
            let conversionRule = this.ratios.findIndex(e => e.value === this.recharge.ratio)+1;
            let res = await this.$http.post('draftbean/accounts/recharge', {
                enterpriseId: this.enterpriseId,
                rechargeAmount: this.recharge.money,
                rechargeDraftBean: this.recharge.sum,
                conversionRule: conversionRule
            })
            return res;
        }

        // event
        onRecharge() {
            this.rechargeDialogVisible = true;
        }

        onModify() {
            this.modifyDialogVisible = true;
        }

        onModifyLog() {
            this.$router.push(`/account/draftbeans/visitlog/${this.enterpriseId}`)
        }

        /**
         * 充值提交
         */
        async onRechargeSubmit(row:Object) {
            if (this.recharge.money == '') {
                this.$alert('请输入充值金额！','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => {}
                })
                return;
            }
            let res = await this.rechargeDraftBeans()
            if (res.status == 200 && res.success) {
                this.rechargeDialogVisible = false;
                this.getBudgetDetailByEId();
                this.getAccountByEId();
            } else {
                this.$message(res.msg);
            }
        }

        /**
         * 修改提交
         */
        async onModifySubmit(row:Object) {
            if (this.modifyForm.beans == '') {
                this.$alert('请输入增减汇票豆的个数！','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => {}
                })
                return;
            }
            let res = await this.updateDraftBeanByEnterpriseId()
            if (res.status == 200 && res.success) {
                this.modifyDialogVisible = false;
                this.getBudgetDetailByEId();
                this.getAccountByEId();
            } else {
                this.$message(res.msg);
            }
        }

        /**
         * 关闭充值弹窗重置
         */
        onCloseRechageDialog() {
            this.recharge = {
                money: '',
                ratio: 1.1,
                sum: ''
            }
        }

        /**
         * 关闭修改弹窗重置
         */
        onCloseModifyDialog() {
            this.modifyForm = {
                beans: '',
                operType: "2",
                explain: ''
            }
        }

        /**
         * 筛选
         */
        onFilterData() {
            this.getBudgetDetailByEId();
        }

        /**
         * 导出Excel
         */
        onExportExcel() {
            window.open(`${location.origin}/boms/draftbean/accounts/export?enterpriseId=${this.accountInfo.enterpriseId}&budget=${this.beansType}&startTime=${this.dateRegion[0]}&endTime=${this.dateRegion[1]}`)
        }

        loadDataForPagination() {
            this.getBudgetDetailByEId()
        }

        // life circle
        mounted() {
            this.getBudgetDetailByEId();
            this.getAccountByEId();
        }
    }
</script>
<style lang="scss" scoped>
    i {
        font-style: normal;
    }
    .font_size_20 {
        font-size: 20px;
        color: $__color-label;
    }
    .blod_style_i {
        color: $__color-show;
    }
</style>
<style lang="scss">
    .income_color {
        color: red; 
    }
    .outgo_color {
        color: #F8D375;
    }
    .text_center {
        font-size: 1.5rem;
        text-align: center;
    }
    .draft_int {
        width: 67% !important;
        .el-input__inner {
            height: 34px;
        }
    }
</style>